<template>
	<div class="home">
		<van-nav-bar title="抗原检测综合系统" />

		<van-form @submit="onSubmit">
			<van-field v-model="form.phone" name="手机号" label="手机号" placeholder="请输入手机号" :rules="telRule" />
			<van-field v-model="form.password" type="password" name="密码" label="密码" placeholder="请输入密码"
				:rules="passwordRule" />
			<div style="margin: 16px;">
				<van-button plain block type="info" native-type="submit">登录</van-button>
			</div>
		</van-form>
		<div style="margin: 16px;">
			<van-button plain block type="primary" @click="registerPhone">注册</van-button>
		</div>

	</div>
</template>

<script>
import {Toast} from "vant";
import userApi from '@/api/userApi'; // 用户数据接口

export default {
  name: 'Login',
  data() {
    return {
      form: {
        phone: '',
        password: '',
      },
      telRule: [{
        required: true,
        message: "请输入手机号",
						trigger: "onBlur"
					},
					{
						validator: value => {
							return /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/.test(value);
						},
						message: "请输入正确格式的11位手机号"
					}
				],
				passwordRule: [{
						required: true,
						message: "请输入密码",
						trigger: "onBlur"
					},
					{
						validator: value => {
							return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value);
						},
						message: "密码必须为6~20位数字+英文字母"
					}
				],
				userInfo: {}
			}
		},
		methods: {
			onSubmit() {
				userApi.login(this.form).then(res => {
					if (res.data.code === 200) { // 登录成功
						// 将token存在localStorage中
						localStorage.setItem("token", res.data.data.token)
						// 设置登录状态
						localStorage.setItem("isLogin", "1")

						// 调用接口查询用户信息
						userApi.queryUserInfo().then(res => {
							if (res.data.code === 200) {
                this.userInfo = JSON.stringify(res.data.data)
                // 将用户信息存储在localStorage
                localStorage.setItem("userInfo", this.userInfo)

                // --------------------
                // 通过身份证号是否设置判断是否是第一次登录
                var identity = res.data.data.identity;
                var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                if (reg.test(identity)) { // 验证通过
                  // 跳转到首页
                  this.$router.push({
                    path: `/antigenHome`
                  })
                } else {
                  // 跳转到设置信息页
                  this.$router.push({
                    path: `/setMessage`
                  })
                }
              }
						})

					} else { // 登录失败
						// 弹出后台返回的错误信息
						Toast(res.data.message)
					}
				})
			},
			registerPhone() {
				this.$router.push('/register')
			},
		}
	}
</script>
